package org.dromara.common.core.utils.ip;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.file.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.File;
import java.io.IOException;

/**
 * 根据ip地址定位工具类，离线方式
 * 参考地址：<a href="https://gitee.com/lionsoul/ip2region/tree/master/binding/java">集成 ip2region 实现离线IP地址定位库</a>
 *
 * @author lishuyan
 */
@Slf4j
public class RegionUtils {

    private static final Searcher SEARCHER;

    static {
        try {
            SEARCHER = initSearcher();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    SEARCHER.close();
                    log.info("IP地址库资源已释放");
                } catch (IOException e) {
                    log.error("释放IP地址库资源失败", e);
                }
            }));
        } catch (Exception e) {
            throw new ServiceException("IP地址库初始化失败");
        }
    }

    private static Searcher initSearcher() throws Exception {
        String fileName = "/ip2region.xdb";
        File existFile = prepareDbFile(fileName);
        return createSearcher(existFile);
    }

    private static File prepareDbFile(String fileName) throws IOException {
        File existFile = FileUtils.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
        if (!FileUtils.exist(existFile)) {
            ClassPathResource fileStream = new ClassPathResource(fileName);
            if (ObjectUtil.isEmpty(fileStream.getStream())) {
                log.error("IP地址库资源未找到：{}", fileName);
                throw new ServiceException("RegionUtils初始化失败，原因：IP地址库数据不存在！");
            }
            log.info("正在复制IP地址库到临时目录: {}", existFile.getAbsolutePath());
            FileUtils.writeFromStream(fileStream.getStream(), existFile);
            if (!FileUtils.exist(existFile)) {
                throw new IOException("IP地址库文件复制失败: " + existFile.getAbsolutePath());
            }
        }
        return existFile;
    }

    private static Searcher createSearcher(File dbFile) throws Exception {
        log.info("正在加载IP地址库文件: {}", dbFile.getPath());
        byte[] cBuff = Searcher.loadContentFromFile(dbFile.getPath());
        Searcher searcher = Searcher.newWithBuffer(cBuff);
        log.info("IP地址库初始化完成");
        return searcher;
    }

    /**
     * 根据IP地址离线获取城市
     */
    public static String getCityInfo(String ip) {
        try {
            ip = ip.trim();
            // 3、执行查询
            String region = SEARCHER.search(ip);
            return region.replace("0|", "").replace("|0", "");
        } catch (Exception e) {
            log.error("IP地址离线获取城市异常 {}", ip);
            return "未知";
        }
    }

}
